package com.eshanren.controller;

import com.eshanren.config.FileProperties;
import com.eshanren.config.ResponseCode;
import com.eshanren.ext.base.BaseController;
import com.eshanren.model.ContractToken;
import com.eshanren.util.Ethipc;
import com.jfinal.core.ActionKey;
import org.ethereum.core.CallTransaction;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigDecimal;


/**
 * 首页controller
 *
 * @author WWF
 */
public class IndexController extends BaseController {

    /**
     * 检测接口可用
     */
    @Override
    public void index() {
        setAttr(CODE, ResponseCode.CODE_SUCCESS);
        setAttr(MESSAGE, "访问正常");
        renderJson();
    }

    @ActionKey("/abi")
    public void getAbi() {
        String token = getPara("token", "");
        ContractToken contractToken = null;
        try {
            contractToken = ContractToken.dao.findByToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            setAttr(CODE, ResponseCode.CODE_FAILURE);
            setAttr("data", "");
            setAttr(MESSAGE, "数据库异常");
            renderJson();
            return;
        }
        if (contractToken == null) {
            setAttr(CODE, ResponseCode.CODE_SUCCESS);
            setAttr("data", "");
            setAttr(MESSAGE, token + "--该代币未开通");
            renderJson();
            return;
        }
        if (contractToken.getAbi() != null) {
            CallTransaction.Contract contract1 = new CallTransaction.Contract(contractToken.getAbi());
            CallTransaction.Function inc = contract1.getByName("transfer");
            String btc = org.bouncycastle.util.encoders.Hex.toHexString(inc.encodeSignatureLong());
            setAttr(CODE, ResponseCode.CODE_FAILURE);
            setAttr("data", btc);
            renderJson();
            return;
        } else {
            setAttr(CODE, ResponseCode.CODE_FAILURE);
            setAttr("data", "a9059cbb");
            renderJson();
            return;
        }

    }


    @ActionKey("/api/address")
    public void blance() {
        String address = getPara("address", "");
        String token = getPara("token", "");
        ContractToken contractToken = null;
        try {
            contractToken = ContractToken.dao.findByToken(token);
        } catch (Exception e) {
            e.printStackTrace();
            setAttr(CODE, ResponseCode.CODE_FAILURE);
            setAttr("data", "");
            setAttr(MESSAGE, "数据库异常");
            renderJson();
            return;
        }
        if (contractToken == null) {
            setAttr(CODE, ResponseCode.CODE_SUCCESS);
            setAttr("data", "");
            setAttr(MESSAGE, token + "--该代币未开通");
            renderJson();
            return;
        }
        Ethipc ethipc = new Ethipc();
        String blance = null;
        try {
            blance = ethipc.getBlance(address, contractToken.getContractAddress());
        } catch (Exception e) {
            e.printStackTrace();
            setAttr(CODE, ResponseCode.CODE_FAILURE);
            setAttr("data", "");
            setAttr(MESSAGE, "rpc异常");
            renderJson();
            return;
        }
        try {
            if (blance != null && !"".equals(blance) && blance.indexOf("undefined") >= 0) {
                String substring = blance.substring(blance.indexOf("undefined") + 11, blance.length() - 3).trim();
                BigDecimal bigDecimal = new BigDecimal(substring);
                String result = "0x" + bigDecimal.toBigInteger().toString(16);
                setAttr(CODE, ResponseCode.CODE_SUCCESS);
                setAttr("data", result);
                renderJson();
                return;
            } else {
                if (blance == null || "".equals(blance)) {
                    setAttr(CODE, ResponseCode.CODE_FAILURE);
                    setAttr("data", "");
                    setAttr(MESSAGE, "rpc异常");
                    renderJson();
                    return;
                } else {
                    setAttr(CODE, ResponseCode.CODE_FAILURE);
                    setAttr(MESSAGE, blance);
                    renderJson();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            renderJson();
        }
    }

    /**
     * 获取地址的交易列表
     */
    @ActionKey("/api/file")
    public void file() {
        readFileByLines(FileProperties.getPath());
    }


    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static void readFileByLines(String fileName) {
        File file = new File(fileName);
        BufferedReader reader = null;
        try {
            System.out.println("以行为单位读取文件内容，一次读一整行：");
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            int line = 1;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                String[] strings = tempString.split("\\|");
                ContractToken contractToken = new ContractToken();
                contractToken.setContractAddress(strings[0].trim());
                contractToken.setPic(strings[1].trim());
                contractToken.setToken(strings[2].trim());
                contractToken.save();
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
    }


}
